import yaml
import os
import redis
from csagent.core.utils import HttpES7

from csagent.core.agent import Agent
from csagent.core.config.schema import AgentConfig, ShortTermConfig
from csagent.core.config.loader import load_agent_config
from csagent.core.builder.graph_builder import GraphBuilder

class AgentBuilder:
    @staticmethod
    def from_yaml(config_path: str) -> Agent:
        config = load_agent_config(config_path)
        graph_builder = GraphBuilder(config)
        graph = graph_builder.build()
        agent = Agent()
        agent.config = config
        agent.graph = graph
        AgentBuilder._init_short_term(agent)
        AgentBuilder._init_long_term(agent)
        return agent
    
    @staticmethod
    def _init_short_term(agent):
        short_term_onfig = agent.config.memory.short_term
        enable = short_term_onfig.read or short_term_onfig.write
        if not enable:
            return
        redis_host = os.environ.get("REDIS_ADDR", "")
        redis_port = int(os.environ.get("REDIS_PORT", 6379))
        redis_pass = os.environ.get("REDIS_PASSWORD", "")
        pool = redis.ConnectionPool(
            host=redis_host, 
            port=int(redis_port), 
            db=0,
            password=redis_pass,
            decode_responses = True,
            max_connections=20  
        )
        agent.redis_cli = redis.Redis(connection_pool=pool)
        if not agent.redis_cli.ping():
            raise RuntimeError("short memory初始化失败: redis连接失败")
        
    @staticmethod
    def _init_long_term(agent):
        long_term_onfig = agent.config.memory.long_term
        enable = long_term_onfig.read
        if not enable:
            return
        es_host = os.environ.get("ES_HOST", "")
        es_user = os.environ.get("ES_USER", "")
        es_pass = os.environ.get("ES_PASSWORD", "")
        agent.es_cli = HttpES7(
            es_host,
            es_user,
            es_pass
        )
        if not agent.es_cli.ping():
            raise RuntimeError("long memory初始化失败: es连接失败")
        












